package com.flyshop.module.user.service;

import com.flyshop.common.utils.BCryptUtil;
import com.flyshop.common.utils.IpUtils;
import com.flyshop.common.utils.UserSessionUtil;
import com.flyshop.core.entity.DataVo;
import com.flyshop.core.entity.PageVo;
import com.flyshop.module.user.dao.UserDao;
import com.flyshop.module.user.model.User;
import com.flyshop.module.user.model.UserGroup;
import com.flyshop.module.webconfig.service.WebConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserDao dao;
    @Autowired
    private WebConfigService configService;

    // ///////////////////////////////
    // /////       增加       ////////
    // ///////////////////////////////
    /**
     * 用户注册基本信息
     *
     * @param username
     *        用户注册登录名
     * @param password
     *        用户注册密码
     * @param request
     * @throws Exception
     */
    @Transactional
    public DataVo addUserReg(String username, String password, HttpServletRequest request) throws Exception {
        User checkuser=this.findByUsername(username);
        if (checkuser != null) {
            return DataVo.failure("该用户已存在，请换其他账户！");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(BCryptUtil.hashpw(password, BCryptUtil.gensalt()));
        user.setTime(new Date());
        //添加用户账号和密码
        int userId = dao.addUser(user);
        //添加用户组权限
        //dao.addUserAndRole(userId,Integer.parseInt(configService.getStringByKey("user_role")));
        User userinfo = dao.findUserById(userId,0);
        UserSessionUtil.setLoginMember(request,userinfo);
        return DataVo.success("操作成功");
    }

    //添加新用户信息
    @Transactional
    public DataVo addUser(User user){
        DataVo data = DataVo.failure("操作失败");
        if(user.getUsername()==null){
            return data=DataVo.success("用户名不能为空！");
        }
        if(user.getPassword()!=null){
            if(!user.getPassword().equals(user.getRepassword())){
                return data=DataVo.success("两次密码不一样");
            }
        }else{
            return data=DataVo.success("新用户密码不能为空！");
        }
        //用户添加时间
        user.setTime(new Date());
        int totalCount = dao.addUser(user);
        if(totalCount > 0){
            data = DataVo.success("新用户添加成功");
        }else{
            data=DataVo.failure("新用户添加失败！");
        }
        return data;
    }

    // ///////////////////////////////
    // /////        刪除      ////////
    // ///////////////////////////////
    //按id删除用户信息
    @Transactional
    public DataVo deleteUserById(int userId){
        DataVo data = DataVo.failure("操作失败");
        int totalCount = dao.deleteUserById(userId);
        if(totalCount > 0){
            data = DataVo.success("已删除用户信息");
        }else{
            data=DataVo.failure("删除失败，请联系管理员！");
        }
        return data;
    }
    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////
    /**
     * 用户登陆
     *
     * @param username
     *        用户名
     * @param password
     *        密码
     * @param request
     * @throws Exception
     */
    @Transactional
    public User userLogin(String username, String password, HttpServletRequest request) {
        User user = dao.findByUsername(username);
        if (user != null) {
            User login = new User();
            if (BCryptUtil.checkpw(password, user.getPassword())) {
                login.setUserId(user.getUserId());
                login.setAttempts(0);
                login.setLastLogin(new Date());
                login.setLoginIp(IpUtils.getIpAddr(request));
                dao.updateUserLogin(login);
                //用户信息写入session
                UserSessionUtil.setLoginMember(request,user);
            }else{
                login.setUserId(user.getUserId());
                login.setAttempts(user.getAttempts()+1);
                login.setAttemptsTime(new Date());
                dao.updateUserLogin(login);
                user = null;
            }
        }
        return user;
    }

    //更新用户信息
    @Transactional
    public DataVo updateUser(User user){
        DataVo data = DataVo.failure("操作失败");
        if(user.getPassword()!=null){
            if(!user.getPassword().equals(user.getRepassword())){
                return data=DataVo.success("两次密码不一样");
            }
        }
        int totalCount = dao.updateUser(user);
        if(totalCount > 0){
            data = DataVo.success("用户信息修改");
        }else{
            data=DataVo.failure("更新失败，请联系管理员！");
        }
        return data;
    }


    // ///////////////////////////////
    // /////        查询      ////////
    // ///////////////////////////////
    /**
     * 通过userId查询用户信息
     * 用户状态0是所有 1未审核 2正常状态 3 删除至回收站 4锁定
     *
     * @param userId
     *         用户id
     * @param  status
     *          审核状态
     * @return User
     */
    public User findUserById(int userId,int status) {
        return dao.findUserById(userId,status);
    }

    /**
     * 通过username查询用户信息
     *
     * @param username
     * @return User
     */
    public User findByUsername(String username) {
        return dao.findByUsername(username);
    }

    /**
     * 用户翻页查询
     *
     * @param pageNum
     * @param rows
     * @return
     * @throws Exception
     */
    public PageVo<User> getUserListPage(String username,String trueName,String mobile,String email,int pageNum, int rows) {
        PageVo<User> pageVo = new PageVo<User>(pageNum);
        pageVo.setRows(rows);
        List<User> list = new ArrayList<User>();
        pageVo.setList(dao.getUserList(username, trueName, mobile, email,pageVo.getOffset(), pageVo.getRows()));
        pageVo.setCount(dao.getUserCount(username, trueName, mobile, email));
        return pageVo;
    }
}
